package project.config;

import javax.servlet.Registration.Dynamic;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class WebConfigInitializer implements WebApplicationInitializer{

	@Override
	public void onStartup(ServletContext servletContext)
			throws ServletException {
		/**
		 * This is annotation(gradle-prefered) style
		 * */
		// Create the root Spring application context 'ctx'
		AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
		ctx.register(WebConfig.class);
		ctx.refresh();
		// Manage the lifecycle of the root application context
		servletContext.addListener(new ContextLoaderListener(ctx));
		ctx.setServletContext(servletContext);
		
//	    // Create the dispatcher servlet's Spring application context
//		AnnotationConfigWebApplicationContext dispatcherCtx = new AnnotationConfigWebApplicationContext();
//		dispatcherCtx.register(DispatcherConfig.class);
		
		// Register and map the dispatcher servlet.(if there is a different dispatcherCtx,it should be add as parameter to DispatcherServlet()
		javax.servlet.ServletRegistration.Dynamic dispatcherServlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
		dispatcherServlet.addMapping("/");
		//Sets the loadOnStartup priority on the Servlet represented by this dynamic ServletRegistration. 
		dispatcherServlet.setLoadOnStartup(1);
		
		/**
		 * if there is anything related, this interface instance will be automatically injected
		 * with entity(similar to Ninject in .Net)
		 **/
	}

}
